<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb-2">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAddScene"
              v-hasPermi="['course:scene:edit']"
            >
              新增场景
            </el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="success"
              plain
              icon="CollectionTag"
              @click="handleLabelTable('0')"
              v-hasPermi="['system:user:add']"
            >
              产品标签库管理
            </el-button>
          </el-col>

          <el-col :span="1.5">
            <el-button
              type="warning"
              plain
              icon="CollectionTag"
              @click="handleLabelTable('1')"
              v-hasPermi="['system:user:add']"
            >
              能力标签库管理
            </el-button>
          </el-col>
          <right-toolbar
            :search="false"
            v-model:showSearch="showSearch"
            @queryTable="getSceneList"
          ></right-toolbar>
        </el-row>
      </template>

      <!-- 场景列表 -->
      <el-row :gutter="4">
        <el-col :span="6">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <div class="text">场景列表</div>
                <el-input
                  v-model="getSceneParams.name"
                  placeholder="请输入场景名称"
                  clearable
                  size="small"
                  width="100"
                />
                <el-button
                  type="primary"
                  size="small"
                  icon="Search"
                  @click="getSceneList"
                  >筛选
                </el-button>
              </div>
            </template>
            <el-table
              highlight-current-row
              :data="sceneList"
              @cell-click="handleSceneClick"
              style="height: 62vh"
              row-class-name="table-row-selectable"
            >
              <el-table-column prop="name" label="场景名称" width="100" />
              <el-table-column label="状态" width="60">
                <template #default="scope">
                  <el-switch
                    size="small"
                    active-value="0"
                    inactive-value="1"
                    @change="switchSceneStatus(scope.row)"
                    :model-value="scope.row.status"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <span v-hasPermi="['course:scene:add']">
                    <el-tooltip
                      content="新增一级分类"
                      placement="top"
                      :enterable="false"
                    >
                      <el-button
                        link
                        type="primary"
                        icon="Plus"
                        @click.stop="handleAddFirstCategory(scope.row)"
                      ></el-button>
                    </el-tooltip>
                  </span>
                  <span v-hasPermi="['system:scene:edit']">
                    <el-tooltip
                      content="编辑"
                      placement="top"
                      :enterable="false"
                    >
                      <el-button
                        link
                        type="primary"
                        icon="Edit"
                        @click.stop="handleSceneEdit(scope.row)"
                      ></el-button>
                    </el-tooltip>
                  </span>
                  <span v-hasPermi="['system:scene:remove']">
                    <el-tooltip
                      content="删除"
                      placement="top"
                      :enterable="false"
                    >
                      <el-button
                        link
                        type="primary"
                        icon="Delete"
                        @click.stop="handleDeleteScene(scope.row)"
                      ></el-button>
                    </el-tooltip>
                  </span>
                </template>
              </el-table-column>
            </el-table>

            <!-- <pagination
              v-show="SceneTotal > 0"
              :total="SceneTotal"
              small
              :layout="'prev, pager, next'"
              v-model:page="SceneParams.pageNum"
              v-model:limit="SceneParams.pageSize"
              @pagination="getSceneList"
            /> -->
          </el-card>
        </el-col>

        <!-- 一级分类列表 -->
        <el-col :span="6">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <div class="text">一级分类</div>
                <el-input
                  size="small"
                  v-model="firstCategoryBo.name"
                  placeholder="请输入分类名称"
                  clearable
                  width="100"
                />
                <el-button
                  size="small"
                  @click="getFirstCategoryList(currentSceneId)"
                  type="primary"
                  icon="Search"
                  >筛选
                </el-button>
              </div>
            </template>
            <el-table
              highlight-current-row
              row-class-name="table-row-selectable"
              style="width: 100%; height: 62vh"
              ref="roleTable"
              :data="firstCategoryList"
              @row-click="handleFirstCategoryClick"
            >
              <el-table-column prop="name" label="分类名" width="100" />
              <el-table-column label="状态" width="60">
                <template #default="scope">
                  <el-switch
                    size="small"
                    active-value="0"
                    inactive-value="1"
                    @change="switchCategoryStatus(scope.row)"
                    :model-value="scope.row.status"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <span v-hasPermi="['system:user:add']">
                    <el-tooltip
                      content="新增二级分类"
                      placement="top"
                      :enterable="false"
                    >
                      <el-button
                        link
                        type="primary"
                        icon="Plus"
                        @click.stop="handleAddSecondCategory(scope.row)"
                      ></el-button>
                    </el-tooltip>
                  </span>
                  <span v-hasPermi="['system:user:edit']">
                    <el-tooltip
                      content="编辑"
                      placement="top"
                      :enterable="false"
                    >
                      <el-button
                        link
                        type="primary"
                        icon="Edit"
                        @click.stop="handleFirstCategoryEdit(scope.row)"
                      ></el-button>
                    </el-tooltip>
                  </span>
                  <span v-hasPermi="['system:user:remove']">
                    <el-tooltip
                      content="删除"
                      placement="top"
                      :enterable="false"
                    >
                      <el-button
                        link
                        type="primary"
                        icon="Delete"
                        @click.stop="handleDeleteFirstCategory(scope.row)"
                      ></el-button>
                    </el-tooltip>
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <!-- 二级分类列表 -->
        <el-col :span="6">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <div class="text">二级分类</div>
                <el-input
                  v-model="getSecondCategoryListBo.name"
                  size="small"
                  placeholder="请输入分类名称"
                  clearable
                  width="100"
                />
                <el-button
                  size="small"
                  type="primary"
                  @click="getSecondCategoryList"
                  icon="Search"
                >
                  筛选
                </el-button>
              </div>
            </template>
            <el-table
              highlight-current-row
              row-class-name="table-row-selectable"
              style="width: 100%; height: 62vh"
              ref="roleTable"
              :data="secondCategoryList"
              @row-click="handleSecondCategoryClick"
            >
              <el-table-column prop="name" label="分类名" width="100" />
              <el-table-column label="状态" width="60">
                <template #default="scope">
                  <el-switch
                    size="small"
                    active-value="0"
                    inactive-value="1"
                    :model-value="scope.row.status"
                    @change="switchCategoryStatus(scope.row)"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-tooltip
                    content="选择标签"
                    placement="top"
                    :enterable="false"
                  >
                    <el-button
                      link
                      type="primary"
                      @click="handleAddLabel(scope.row)"
                    >
                      <icon-ic-baseline-list-alt />
                    </el-button>
                  </el-tooltip>
                  <span v-hasPermi="['system:user:add']">
                    <el-tooltip
                      content="编辑"
                      placement="top"
                      :enterable="false"
                    >
                      <el-button
                        link
                        type="primary"
                        icon="Edit"
                        @click.stop="handleSecondCategoryEdit(scope.row)"
                      >
                      </el-button>
                    </el-tooltip>
                  </span>
                  <span v-hasPermi="['system:user:remove']">
                    <el-tooltip
                      content="删除"
                      placement="top"
                      :enterable="false"
                    >
                      <el-button
                        link
                        type="primary"
                        icon="Delete"
                        @click.stop="handleDeleteSecondCategory(scope.row)"
                      ></el-button>
                    </el-tooltip>
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <!-- 标签列表 -->
        <el-col :span="6">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <div class="text">标签</div>
                <el-input
                  size="small"
                  placeholder="请输入标签名称"
                  clearable
                  width="100"
                />
                <el-button size="small" type="primary" icon="Search"
                  >筛选
                </el-button>
              </div>
            </template>
            <el-table
              style="width: 100%; height: 62vh"
              ref="roleTable"
              :data="categoryLabelList"
            >
              <el-table-column prop="name" label="标签名" width="150" />
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <span v-hasPermi="['system:user:edit']">
                    <el-tooltip
                      content="编辑"
                      :enterable="false"
                      placement="top"
                    >
                      <el-button
                        link
                        icon="Edit"
                        type="primary"
                        @click="handleEditLabel(scope.row)"
                      ></el-button>
                    </el-tooltip>
                  </span>
                  <span class="pl-10px">
                    <el-tooltip
                      content="移出"
                      :enterable="false"
                      placement="top"
                    >
                      <el-button
                        link
                        type="primary"
                        @click="removeLabelFromCategory(scope.row)"
                      >
                        <template #icon>
                          <icon-ic-baseline-remove-circle-outline />
                        </template>
                      </el-button>
                    </el-tooltip>
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>

  <!-- 新增分类 -->
  <el-dialog
    v-model="categoryDialogStatus.isShow"
    :title="categoryDialogStatus.title"
    width="30%"
    center
    :show-close="false"
    :close-on-click-modal="false"
    @close="categoryClose"
  >
    <el-form
      :model="addCategoryParams"
      ref="dialogFormRef"
      :inline="true"
      label-width="100px"
      class="dialogForm"
      :rules="categoryFormRules"
    >
      <el-form-item label="分类名称" prop="name">
        <el-input
          v-model="addCategoryParams.name"
          placeholder="请输入名称"
          clearable
          style="width: 220px"
        />
        <!--        :disabled="categoryDialogStatus.isDisabled"-->
      </el-form-item>
      <el-form-item label="排序" prop="orderNum">
        <el-input-number v-model="addCategoryParams.rank" :min="1" :max="10" />
      </el-form-item>

      <el-form-item label="分类状态" prop="name">
        <el-radio-group v-model="addCategoryParams.status" class="ml-4">
          <el-radio label="0" size="large">正常</el-radio>
          <el-radio label="1" size="large">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="addCategoryParams.remark"
          placeholder="请输入"
          clearable
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
          style="width: 220px"
        />
      </el-form-item>

      <el-form-item class="dialogFooter">
        <el-button
          v-if="categoryDialogStatus.mode === DialogModeEnum.NEW"
          type="primary"
          icon="Search"
          @click="handleAddSubmit"
        >
          提交
        </el-button>
        <el-button
          v-if="categoryDialogStatus.mode === DialogModeEnum.EDIT"
          type="primary"
          icon="Search"
          @click="handleEditSubmit"
        >
          保存
        </el-button>
        <el-button icon="Refresh" @click="closeCategoryDialog">关闭</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 新增场景 -->
  <el-dialog
    v-model="sceneDialogStatus.isShow"
    :title="sceneDialogStatus.title"
    width="30%"
    center
    :show-close="false"
    :close-on-click-modal="false"
    @close="sceneClose"
  >
    <el-form
      :model="addSceneBo"
      ref="dialogFormRef"
      :inline="true"
      label-width="100px"
      class="dialogForm"
      :rules="sceneFormRules"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="addSceneBo.name"
          placeholder="请输入名称"
          clearable
          style="width: 220px"
        />
        <!--        :disabled="dialogStatus.isDisabled"-->
      </el-form-item>
      <el-form-item label="排序" prop="orderNum">
        <el-input-number v-model="addSceneBo.orderNum" :min="1" :max="10" />
      </el-form-item>

      <el-form-item label="场景状态" prop="name">
        <el-radio-group v-model="addSceneBo.status" class="ml-4">
          <el-radio label="0" size="large">正常</el-radio>
          <el-radio label="1" size="large">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="场景备注" prop="remark">
        <el-input
          v-model="addSceneBo.remark"
          placeholder="请输入"
          clearable
          type="textarea"
          :autosize="{ minRows: 4, maxRows: 8 }"
        />
      </el-form-item>

      <el-form-item class="dialogFooter">
        <el-button
          v-if="sceneDialogStatus.mode === DialogModeEnum.NEW"
          type="primary"
          icon="Search"
          @click="handleAddSubmit"
        >
          提交
        </el-button>
        <el-button
          v-if="sceneDialogStatus.mode === DialogModeEnum.EDIT"
          type="primary"
          icon="Search"
          @click="handleEditSubmit"
        >
          保存
        </el-button>
        <el-button icon="Refresh" @click="closeSceneDialog">关闭</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 新增标签 -->
  <!--  <el-dialog-->
  <!--    v-model="labelDialogStatus.isShow"-->
  <!--    :title="labelDialogStatus.title"-->
  <!--    width="30%"-->
  <!--    center-->
  <!--    :show-close="false"-->
  <!--    :close-on-click-modal="false"-->
  <!--  >-->
  <!--    <el-form-->
  <!--      :model="addListLabelBo"-->
  <!--      ref="dialogFormRef"-->
  <!--      :inline="true"-->
  <!--      Label-width="100px"-->
  <!--      class="dialogForm"-->
  <!--    >-->
  <!--      <el-form-item label="标签名称" prop="name">-->
  <!--        <el-input-->
  <!--          v-model="addListLabelBo.name"-->
  <!--          placeholder="请输入名称"-->
  <!--          clearable-->
  <!--          style="width: 220px"-->
  <!--        />-->
  <!--&lt;!&ndash;        :disabled="dialogStatus.isDisabled"&ndash;&gt;-->
  <!--      </el-form-item>-->

  <!--      &lt;!&ndash; <el-form-item label="排序" prop="orderNum">-->
  <!--        <el-input-number v-model="addListLabelBo.orderNum" :min="1" :max="10" />-->
  <!--      </el-form-item> &ndash;&gt;-->

  <!--      <el-form-item label="标签状态1" prop="name">-->
  <!--        <el-radio-group v-model="addListLabelBo.status" class="ml-4">-->
  <!--          <el-radio label="0" size="large">正常</el-radio>-->
  <!--          <el-radio label="1" size="large">停用</el-radio>-->
  <!--        </el-radio-group>-->
  <!--      </el-form-item>-->

  <!--      <el-form-item class="dialogFooter">-->
  <!--        <el-button type="primary" icon="Search" @click="addLabelSubmit">-->
  <!--          提交-->
  <!--        </el-button>-->
  <!--        <el-button icon="Refresh" @click="closeInnerDialog">关闭</el-button>-->
  <!--      </el-form-item>-->
  <!--    </el-form>-->
  <!--  </el-dialog>-->

  <!-- 编辑、新增标签 -->
  <el-dialog
    v-model="labelDialogStatus.isShow"
    :title="labelDialogStatus.title"
    width="30%"
    center
    :show-close="false"
    :close-on-click-modal="false"
    @close="closeLabelDialog"
  >
    <el-form
      :model="addListLabelBo"
      ref="dialogFormRef"
      :inline="true"
      Label-width="100px"
      class="dialogForm"
    >
      <el-form-item label="标签名称" prop="name">
        <el-input
          v-model="addListLabelBo.name"
          placeholder="请输入名称"
          clearable
          style="width: 220px"
        />
        <!--        :disabled="dialogStatus.isDisabled"-->
      </el-form-item>

      <!-- <el-form-item label="排序" prop="orderNum">
        <el-input-number v-model="addListLabelBo.orderNum" :min="1" :max="10" />
      </el-form-item> -->

      <el-form-item label="标签状态" prop="name">
        <el-radio-group v-model="addListLabelBo.status" class="ml-4">
          <el-radio label="0" size="large">正常</el-radio>
          <el-radio label="1" size="large">停用</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 上传图片 -->
      <el-form-item label="标签图片">
        <el-upload
          list-type="picture-card"
          class="avatar-uploader"
          action="#"
          :accept="'image/png, image/jpeg'"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
        >
          <div style="width: 100%; height: 100%; position: relative">
            <div
              v-if="dialogImageUrl"
              style="width: 100%; height: 100%;"
            >
              <img
                style="
                  position: absolute;
                  top: 0;
                  left: 0;
                  width: 100%;
                  height: 100%;
                  object-fit: scale-down;
                "
                :src="dialogImageUrl"
                alt="label-preview"
              />
            </div>
            <div class="w-100% h-100% flex justify-center mb-8px" v-else>
              <el-tooltip content="选择图片" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="UploadFilled"
                  size="large"
                ></el-button>
              </el-tooltip>
            </div>
          </div>

          <!-- <el-icon class="avatar-uploader-icon">
            <Plus />
          </el-icon> -->
        </el-upload>
        <div style="display: flex; margin: 10px 0 0 3vw">
          <el-button
            link
            icon="UploadFilled"
            type="success"
            :disabled="!isSelected2"
            @click="handleUpload"
            >上传
          </el-button>
          <el-button
            link
            icon="View"
            type="primary"
            :disabled="!isSelected"
            @click="handlePictureCardPreview"
            >查看
          </el-button>
          <!-- <el-button link icon="UploadFilled">重传</el-button> -->
          <div v-show="isFinishUpload" style="color: green; margin-left: 20px">
            已成功上传√
          </div>
        </div>

        <!-- 查看图片 -->
        <el-dialog v-model="labelDialogStatus.isShowPreviewImage">
          <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
      </el-form-item>

      <el-form-item class="dialogFooter">
        <el-button type="primary" icon="Search" @click="handleAddLabelSubmit">
          提交
        </el-button>
        <el-button icon="Refresh" @click="labelDialogStatus.isShow = false">
          关闭
        </el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 标签库管理 -->
  <el-dialog
    v-model="labelManagementDialogStatus.isShow"
    :title="labelManagementDialogStatus.title"
    width="60%"
    center
    :close-on-click-modal="false"
    default-sort="createTime"
    @close="closeLabelManagementDialog"
  >
    <template #header="{ titleClass, titleId }">
      <el-row justify="center" align="middle" class="mb-2">
        <el-col :span="24">
          <div :id="titleId" :class="titleClass">
            {{ labelManagementDialogStatus.title }}
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAddTableLabel"
            v-hasPermi="['system:user:add']"
          >
            新增
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Edit"
            :disabled="labelManagementDialogStatus.single"
            @click="handleEditLabel()"
            v-hasPermi="['system:user:edit']"
          >
            修改
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="labelManagementDialogStatus.multiple"
            @click="handleDeleteLabel()"
            v-hasPermi="['system:user:remove']"
          >
            删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            :disabled="labelManagementDialogStatus.multiple"
            @click="handleAddLabelsToCategory"
            v-show="
              labelManagementDialogStatus.mode ===
              LabelManagementDialogModeEnum.SELECT
            "
            v-hasPermi="['system:user:add']"
          >
            <template #icon>
              <icon-ic-baseline-add-circle-outline />
            </template>
            添加
          </el-button>
        </el-col>
        <right-toolbar
          v-model:showSearch="showSearch"
          :search="false"
          @queryTable="getLabelList"
        >
        </right-toolbar>
      </el-row>
    </template>
    <el-table
      highlight-current-row
      style="width: 100%"
      ref="roleTable"
      :data="labelList"
      @selection-change="handleLabelManageSelectionChange"
    >
      <el-table-column type="selection" width="30" align="center" />
      <el-table-column prop="name" label="标签名" width="120" />
      <el-table-column prop="createBy" label="创建者" width="120" />
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="160"
        sortable
      />

      <el-table-column
        label="状态"
        width="80"
        v-if="
          labelManagementDialogStatus.mode ===
          LabelManagementDialogModeEnum.MANAGE
        "
      >
        <template #default="scope">
          <el-switch
            active-value="0"
            inactive-value="1"
            @change="switchLabelStatus(scope.row)"
            v-model="scope.row.status"
          />
        </template>
      </el-table-column>

      <el-table-column prop="associationCourseNum" label="关联课程" />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <span class="pl-5" v-hasPermi="['system:user:edit']">
            <el-tooltip
              content="添加"
              :enterable="false"
              placement="top"
              v-if="
                labelManagementDialogStatus.mode ===
                LabelManagementDialogModeEnum.SELECT
              "
            >
              <el-button
                link
                type="primary"
                @click="addLabelToCategory(scope.row)"
              >
                <template #icon>
                  <icon-ic-baseline-add-circle-outline />
                </template>
              </el-button>
            </el-tooltip>
          </span>
          <span class="pl-5" v-hasPermi="['system:user:edit']">
            <el-tooltip
              content="编辑"
              :enterable="false"
              placement="top"
              v-if="
                labelManagementDialogStatus.mode ===
                LabelManagementDialogModeEnum.MANAGE
              "
            >
              <el-button
                icon="Edit"
                link
                type="primary"
                @click="handleEditLabel(scope.row)"
              >
              </el-button>
            </el-tooltip>
          </span>
          <span class="pl-5" v-hasPermi="['system:user:remove']">
            <el-tooltip content="删除" :enterable="false" placement="top">
              <el-button
                v-if="
                  labelManagementDialogStatus.mode ===
                  LabelManagementDialogModeEnum.MANAGE
                "
                link
                icon="Delete"
                type="primary"
                @click="handleDeleteLabel(scope.row)"
              >
              </el-button>
            </el-tooltip>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <template #footer>
      <pagination
        v-show="total > 0"
        :total="total"
        :page-sizes="[5, 10, 15, 20]"
        v-model:page="getLabelParams.pageNum"
        v-model:limit="getLabelParams.pageSize"
        @pagination="getLabelList"
      />
      <!--      :pager-count="3"-->
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  addCategoryLabel as addLabelToCategoryApi,
  addFirstCategory as addFirstCategoryApi,
  addLabel as addLabelApi,
  addLabelsToCategory as addLabelsToCategoryApi,
  addScene as addSceneApi,
  addSecondCategory as addSecondCategoryApi,
  delLabel as delLabelApi,
  getCategoryDetail as getCategoryDetailApi,
  getFirstCategoryList as getFirstCategoryListApi,
  getLabelById as getLabelByIdApi,
  getLabelCourseCount as getLabelCourseCountApi,
  getLabelDetail as getLabelDetailApi,
  getOssAuth as getOssAuthApi,
  getSceneDetail as getSceneDetailApi,
  getSceneList as getSceneListApi,
  getSecondCategoryList as getSecondCategoryListApi,
  getTagList as getLabelListApi,
  deleteCategory as deleteCategoryApi,
  deleteScene as deleteSceneApi,
  postToOSS as postToOSSApi,
  removeLabelsFromCategory as removeLabelFromCategoryApi,
  switchCategory as switchCategoryApi,
  switchScene as switchSceneApi,
  updateCategoryDetail as updateCategoryDetailApi,
  updateLabel as updateLabelApi,
  updateLabelStatus as updateLabelStatusApi,
  updateSceneDetail as updateSceneDetailApi,
} from "@/service/api/course/tag/index";

import { ElForm } from "element-plus";
import { to } from "await-to-js";
import RightToolbar from "@/components/RightToolbar/index.vue";
import Pagination from "@/components/Pagination/index.vue";
import { BasePageResponse, BaseResponse } from "@/service/api/type.ts";
import {
  CourseCategoryVo,
  CourseLabelVo,
  CourseSceneVo,
  UploadAuthVo,
} from "@/service/api/course/tag/types.ts";
import { DialogModeEnum } from "@/enums/dialogEnum.ts";
import { LabelManagementDialogModeEnum } from "@/views/courseManagement/courseTag/types.ts";

const showSearch = ref(true);
const labelList = ref<CourseLabelVo[]>([]);
const sceneList = ref<CourseSceneVo[]>([]);
const firstCategoryList = ref<CourseCategoryVo[]>([]);
const secondCategoryList = ref<CourseCategoryVo[]>([]);
const categoryLabelList = ref<CourseLabelVo[]>([]);
const dialogFormRef = ref();
const total = ref(0);

// 初始query数据
const initGetLabelParams = {
  pageSize: 5,
  pageNum: 1,
  type: "",
  orderByColumn: "createTime",
  orderType: "desc",
};

const getSceneParams = ref({
  // pageSize: 5,
  // pageNum: 1,
  name: "",
  orderByColumn: "createTime",
  orderType: "desc",
});

const initSceneDialogStatus = {
  isShow: false,
  title: "",
  mode: DialogModeEnum.NEW,
};

const initCategoryDialogStatus = {
  isShow: false,
  title: "",
  mode: DialogModeEnum.NEW,
};

const initLabelDialogStatus = {
  isShow: false,
  title: "",
  mode: DialogModeEnum.NEW,
  isShowPreviewImage: false,
};

const initLabelManagementDialogStatus = {
  isShow: false,
  title: "",
  mode: LabelManagementDialogModeEnum.MANAGE,
  ids: <string[]>[],
  single: true,
  multiple: true,
  associationCourseNum: 0,
};

// 初始dialog状态
// const initDialogStatus = {
//   // 标签列表
//   isLabelTable: false,
//   // 列表里的dialog
//   isLabel: false,
//   // 添加场景
//   isScene: false,
//   // 添加分类
//   isCategory: false,
//   // 编辑分类
//   isUpdate: false,
//   isInnerDialog: false,
//   title: "",
//   isDisabled: false,
//   innerTitle: "",
//   // 预览图片
//   preview: false,
// };

/**
 * 新增场景BO
 */
const initAddSceneBo: CourseSceneVo = {
  id: "",
  name: "",
  orderNum: 0,
  remark: "",
  status: "0",
  parentId: "",
};

/**
 * 新增分类BO
 */
const initAddCategoryParams: CourseCategoryVo & { sceneId?: string } = {
  name: "",
  rank: 0,
  remark: "",
  status: "0",
  sceneId: "",
};

/**
 * 获取二级分类的BO
 */
const initGetSecondCategoryListBo = {
  parentId: 0,
  name: "",
  orderByColumn: "createTime",
  orderType: "desc",
};

/**
 * 将标签添加到分类的BO
 */
const initAddLabelBo = {
  labelId: "",
  categoryId: "",
};

/**
 * 移出二级分类标签Bo
 */
const initRemoveLabelFromCategoryBo = {
  labelId: "",
  categoryId: "",
};

/**
 * 批量添加标签到分类BO
 */
const initAddLabelsToCategoryBo = {
  labelIds: <string[]>[],
  categoryId: "",
};

/**
 * 标签库新增标签BO
 */
const initAddListLabelBo: CourseLabelVo = {
  name: "",
  orderNum: 0,
  status: "0",
  url: "",
  type: "",
};

/**
 * 修改标签状态BO
 */
const initUpdateLabelStatusBo = {
  id: 0,
  name: "",
  status: "",
  url: "",
};

const sceneFormRules = {
  name: [
    {
      required: true,
      message: "请输入场景名称",
      trigger: "blur",
    },
  ],
};

const categoryFormRules = {
  name: [
    {
      required: true,
      message: "请输入分类名称",
      trigger: "blur",
    },
  ],
};

const data = reactive({
  getLabelParams: { ...initGetLabelParams },
  sceneDialogStatus: { ...initSceneDialogStatus },
  categoryDialogStatus: { ...initCategoryDialogStatus },
  labelDialogStatus: { ...initLabelDialogStatus },
  labelManagementDialogStatus: { ...initLabelManagementDialogStatus },
  addCategoryParams: { ...initAddCategoryParams },
  getSecondCategoryListBo: { ...initGetSecondCategoryListBo },
  addSceneBo: { ...initAddSceneBo },
  addLabelBo: { ...initAddLabelBo },
  addLabelsBo: {
    ...initAddLabelsToCategoryBo,
  },
  addListLabelBo: { ...initAddListLabelBo },
  updateLabelStatusBo: { ...initUpdateLabelStatusBo },
  moveLabelBo: {
    ...initRemoveLabelFromCategoryBo,
  },
});
const {
  getLabelParams,
  sceneDialogStatus,
  categoryDialogStatus,
  labelDialogStatus,
  labelManagementDialogStatus,
  addCategoryParams,
  getSecondCategoryListBo,
  addSceneBo,
  addLabelBo,
  addListLabelBo,
  addLabelsBo,
  updateLabelStatusBo,
  moveLabelBo,
} = toRefs(data);

// 分页total
const sceneTotal = ref(0);

/**
 * 获取所有场景分类
 */
const getSceneList = async (): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<CourseSceneVo>, any>(
    getSceneListApi(getSceneParams.value),
  );
  if (!err) {
    console.log(res);
    sceneList.value = res?.rows ?? [];
    sceneTotal.value = Number(res?.total ?? 0);

    // 当前选中的场景已经不在场景列表中
    if (!sceneList.value.find((item) => item.id === currentSceneId.value)) {
      firstCategoryList.value = [];
      secondCategoryList.value = [];
      categoryLabelList.value = [];
    }
    return true;
  }
  return false;
};

/**
 * 修改标签状态
 * @param query
 */
const updateLabelStatus = async (query: any) => {
  const [err, res] = await to(updateLabelStatusApi(query));
  if (!err) {
    console.log(res);
    ElMessage({
      message: "更新成功",
      type: "success",
    });
  }
};

/**
 * 标签状态改变
 * @param row
 */
const switchLabelStatus = async (row: any) => {
  console.log(row);
  updateLabelStatusBo.value = row;
  await updateLabelStatus(updateLabelStatusBo.value);
  const response = await getLabelList();
  if (response) {
    ElMessage({
      message: "列表更新成功",
      type: "success",
    });
  }
};

/**
 * 标签库管理勾选
 * @param selection
 */
const handleLabelManageSelectionChange = (selection: CourseLabelVo[]) => {
  labelManagementDialogStatus.value.ids = selection.map(
    (item: CourseLabelVo) => item.id ?? "",
  );
  labelManagementDialogStatus.value.single = selection.length != 1;
  labelManagementDialogStatus.value.multiple = !selection.length;
  labelManagementDialogStatus.value.associationCourseNum = selection.reduce(
    (acc: number, item: CourseLabelVo) =>
      acc + (item.associationCourseNum ?? 0),
    0,
  );

  console.log(selection);
};

/**
 * 根据id获取标签详情
 * @param id
 */
const getLabelDetail = async (id: string): Promise<boolean> => {
  const [err, res] = await to<BaseResponse<CourseLabelVo>, any>(
    getLabelDetailApi(id),
  );
  if (!err) {
    isSelected2.value = false
    console.log(res);
    addListLabelBo.value = res?.data ?? initAddListLabelBo;
    if (res?.data?.url) {
      dialogImageUrl.value = res.data.url;
      isFinishUpload.value = true;
      isSelected.value = true

    }
    return true;
  }
  return false;
};

/**
 * 标签库编辑按钮
 * @param row
 */
const handleEditLabel = async (row?: any) => {
  // 询问是否编辑
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm(
      "编辑该标签将改变所有使用该标签的分类，是否确定编辑该标签？",
      "提示",
      {
        type: "warning",
        confirmButtonText: "是",
        cancelButtonText: "否",
      },
    ),
  );

  if (err === "cancel") {
    // 提示取消编辑
    ElMessage({
      message: "已取消编辑",
      type: "info",
    });
  } else if (confirm === "confirm") {
    const id = row?.id || labelManagementDialogStatus.value.ids[0];
    const response = await getLabelDetail(id);
    if (response) {
      labelDialogStatus.value.title = "编辑标签";
      labelDialogStatus.value.isShow = true;
      labelDialogStatus.value.mode = DialogModeEnum.EDIT;
    }
  }
};

/**
 * 删除标签
 * @param row
 */
const handleDeleteLabel = async (row?: any) => {
  let message = "是否确定删除选中的标签？";
  // 单个删除
  if (row) {
    let count = 0;
    const [countErr, res] = await to<BaseResponse<number>, any>(
      getLabelCourseCountApi(row.id),
    );
    if (!countErr) {
      count = res?.data ?? 0;
    }
    if (count > 0) {
      message = `当前标签下有${count}门课程，是否确定删除选中的标签？`;
    }
  }
  // 批量删除
  else {
    if (labelManagementDialogStatus.value.associationCourseNum > 0) {
      message = `当前选中的标签下共有${labelManagementDialogStatus.value.associationCourseNum}门课程，是否确定删除选中的标签？`;
    }
  }
  // 弹出删除确认框
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm(message, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消删除",
    });
  } else if (confirm === "confirm") {
    const _ids = row?.id || labelManagementDialogStatus.value.ids;
    const [err, res] = await to(delLabelApi(_ids));
    if (!err) {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      labelManagementDialogStatus.value.associationCourseNum = 0;
      console.log(res);
    }
  }
  getLabelList();
};

/**
 * 获取一级分类
 */
const firstCategoryBo = ref({
  name: "",
  orderByColumn: "createTime",
  orderType: "desc",
});

/**
 * 获取一级分类
 * @param id
 */
const getFirstCategoryList = async (id: string): Promise<boolean> => {
  console.log(currentSceneId.value);
  const [err, res] = await to<BaseResponse<CourseCategoryVo[]>, any>(
    getFirstCategoryListApi(id, firstCategoryBo.value),
  );
  if (!err) {
    console.log(res);
    firstCategoryList.value = res?.data ?? [];
    secondCategoryList.value = [];
    categoryLabelList.value = [];
    return true;
  }
  return false;
};

/**
 * 获取二级分类
 */
const getSecondCategoryList = async (): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<CourseCategoryVo>, any>(
    getSecondCategoryListApi(getSecondCategoryListBo.value),
  );
  if (!err) {
    console.log(res);
    secondCategoryList.value = res?.rows ?? [];
    categoryLabelList.value = [];
    return true;
  }
  return false;
};

/**
 * 获取分类下的标签
 * @param id
 */
const getLabelsBySecondCategoryId = async (id: string): Promise<boolean> => {
  const [err, res] = await to<BaseResponse<CourseLabelVo[]>, any>(
    getLabelByIdApi(id),
  );
  if (!err) {
    console.log(res);
    categoryLabelList.value = res?.data ?? [];
    return true;
  }
  return false;
};

/**
 * 添加单个标签到分类
 * @param row
 */
const addLabelToCategory = async (row: any) => {
  addLabelBo.value.labelId = row.id;
  const [err, res] = await to(addLabelToCategoryApi(addLabelBo.value));
  if (!err) {
    console.log(addLabelBo.value, res);
    ElMessage({
      message: "添加成功",
      type: "success",
    });
    getLabelParams.value = Object.assign({}, initGetLabelParams);
    labelManagementDialogStatus.value.isShow = false;
    getLabelList();
    getLabelsBySecondCategoryId(currentSecondCategoryId.value);
  }
};

// 预览图片地址
const dialogImageUrl = ref<string | undefined>();
// 是否已选择图片
const isSelected = ref(false);
const isSelected2 = ref(false)
// 是否已上传成功
const isFinishUpload = ref(false);
// 标签图片
const tagImg = ref();
// 超出一个文件时调用
// const handleExceed: UploadProps["onExceed"] = (files) => {
//   // 手动加入一个文件
//   console.log(tagImg.value);
//   upload.value!.handleStart(tagImg.value);
//   // 清除文件
//   upload.value!.clearFiles();
//   const file = files[0] as UploadRawFile;
//   file.uid = genFileId();
//   upload.value!.handleStart(file);
// };

// 选择文件改变时调用
// const handChange = (uploadFile: any) => {
//   console.log(uploadFile);
//   tagImg.value = uploadFile;
//   // isUploading1.value = true;
//   // isfinish4.value = false;
// };

/**
 * 预览图片
 */
const handlePictureCardPreview = () => {
  labelDialogStatus.value.isShowPreviewImage = true;
};

/**
 * 获取凭证的BO
 */
const getOssAuthBO = reactive({
  originalFileName: "",
});

/**
 * 获取上传凭证
 */
const getOssAuth = async (): Promise<boolean> => {
  const [err, res] = await to<BaseResponse<UploadAuthVo>, any>(
    getOssAuthApi(getOssAuthBO),
  );

  if (!err) {
    console.log(res);
    tagImgParams.value = res?.data ?? {};

    return true;
  }
  return false;
};

const beforeAvatarUpload = (file: any) => {
  // 拿到图片
  tagImg.value = file;
  dialogImageUrl.value = URL.createObjectURL(file);
  console.log(tagImg.value, dialogImageUrl.value);
  isSelected.value = true;
  isSelected2.value = true;
  isFinishUpload.value = false;
  return false;
};

const tagImgParams = ref<UploadAuthVo>({
  OSSAccessKeyId: "",
  callback: "",
  expire: 0,
  host: "",
  policy: "",
  service: "",
  signature: "",
  key: "",
  file: "",
});

/**
 * 结构图片上传按钮
 */
const handleUpload = async () => {
  getOssAuthBO.originalFileName = (tagImg.value as any).name;
  await getOssAuth();
  const formData = new FormData();
  formData.append("key", tagImgParams.value.key ?? "");
  formData.append("OSSAccessKeyId", tagImgParams.value.OSSAccessKeyId ?? "");
  formData.append("policy", tagImgParams.value.policy ?? "");
  formData.append("signature", tagImgParams.value.signature ?? "");
  formData.append("success_action_status", "200"); // 上传成功返回的状态码，不设置则是204
  formData.append("callback", tagImgParams.value.callback ?? "");
  formData.append("file", tagImg.value); // 一定在最后
  console.log(formData);
  const [err, res] = await to(postToOSSApi(formData));
  if (!err) {
    console.log(res);
    if (res.status === 200) {
      if (res.data.code === 200) {
        // 拿到url
        addListLabelBo.value.url = res.data.data.url;
        isFinishUpload.value = true;
        ElMessage({
          type: "success",
          message: "上传成功。",
        });
      }
    }
  } else {
    ElMessage({
      type: "error",
      message: "上传失败,请联系管理员。",
    });
  }
};

/**
 * 批量添加标签到分类
 */
const handleAddLabelsToCategory = async () => {
  addLabelsBo.value.labelIds = labelManagementDialogStatus.value.ids;
  const [err, res] = await to(addLabelsToCategoryApi(addLabelsBo.value));
  if (!err) {
    console.log(res);
    ElMessage({
      message: "新增成功",
      type: "success",
    });
    labelManagementDialogStatus.value.ids = [];
    labelManagementDialogStatus.value.isShow = false;
    getLabelParams.value = Object.assign({}, initGetLabelParams);
    getLabelList();
    getLabelsBySecondCategoryId(currentSecondCategoryId.value);
  }
};

/**
 * 新增场景按钮
 */
const handleAddScene = () => {
  sceneDialogStatus.value.isShow = true;
  sceneDialogStatus.value.title = "新增场景";
  sceneDialogStatus.value.mode = DialogModeEnum.NEW;
};

/**
 * 管理标签按钮
 */
const handleLabelTable = async (type: string) => {
  labelManagementDialogStatus.value.title = (type == '0' ? "产品" : "能力") + "标签库管理";
  getLabelParams.value.type = type;
  addListLabelBo.value.type = type;
  const response = await getLabelList();
  if (response) {
    labelManagementDialogStatus.value.isShow = true;
  }
};

/**
 * 场景列表被点击
 * @param row
 */
const handleSceneClick = (row: any) => {
  console.log(row.id);
  // 如果当前场景与点击的场景不同
  if (currentSceneId.value != row.id) {
    // 初始化其他列表
    secondCategoryList.value = [];
    categoryLabelList.value = [];
  }
  getFirstCategoryList(row.id);
  currentSceneId.value = row.id;
};

/**
 * 一级分类列表被点击
 * @param row
 */
const handleFirstCategoryClick = (row: any) => {
  if (currentFirstCategoryId.value != row.id) {
    categoryLabelList.value = [];
  }
  getSecondCategoryListBo.value.parentId = row.id;
  getSecondCategoryList();
  currentFirstCategoryId.value = row.id;
};

/**
 * 二级分类被点击
 * @param row
 */
const handleSecondCategoryClick = (row: any) => {
  getLabelsBySecondCategoryId(row.id);
  moveLabelBo.value.categoryId = row.id;
  currentSecondCategoryId.value = row.id;
};

const currentSceneId = ref("");
const currentFirstCategoryId = ref("");
const currentSecondCategoryId = ref("");

/**
 * 场景列表新增按钮
 * @param row
 */
const handleAddFirstCategory = (row: any) => {
  console.log(row);
  categoryDialogStatus.value.isShow = true;
  categoryDialogStatus.value.title = "新增一级分类";
  categoryDialogStatus.value.mode = DialogModeEnum.NEW;
  delete addCategoryParams.value.parentId;
  addCategoryParams.value.sceneId = row.id;
};

/**
 * 获取场景详情
 * @param id
 */
const getSceneDetail = async (id: string): Promise<boolean> => {
  const [err, res] = await to(getSceneDetailApi(id));
  if (!err) {
    addSceneBo.value = res?.data ?? initAddSceneBo;
    console.log(res.data);
    return true;
  }
  return false;
};

/**
 * 获取分类详情
 * @param id
 */
const getCategoryDetail = async (id: string): Promise<boolean> => {
  const [err, res] = await to<BaseResponse<CourseCategoryVo>, any>(
    getCategoryDetailApi(id),
  );
  if (!err) {
    console.log(res);
    addCategoryParams.value = res?.data ?? initAddCategoryParams;
    return true;
  }
  return false;
};

/**
 * 处理场景编辑
 * @param row
 */
const handleSceneEdit = async (row: any) => {
  const response = await getSceneDetail(row.id);
  if (response) {
    sceneDialogStatus.value.isShow = true;
    sceneDialogStatus.value.title = "编辑场景";
    sceneDialogStatus.value.mode = DialogModeEnum.EDIT;
  }
};

/**
 * 处理一级分类编辑
 * @param row
 */
const handleFirstCategoryEdit = async (row: any) => {
  const response = await getCategoryDetail(row.id);
  if (response) {
    categoryDialogStatus.value.isShow = true;
    categoryDialogStatus.value.title = "编辑一级分类";
    categoryDialogStatus.value.mode = DialogModeEnum.EDIT;
    console.log(row);
  }
};

/**
 * 处理二级分类编辑
 * @param row
 */
const handleSecondCategoryEdit = async (row: any) => {
  const response = await getCategoryDetail(row.id);
  if (response) {
    categoryDialogStatus.value.isShow = true;
    categoryDialogStatus.value.title = "编辑二级分类";
    categoryDialogStatus.value.mode = DialogModeEnum.EDIT;
    console.log(row);
  }
};

/**
 * 一级分类列表新增按钮
 * @param row
 */
const handleAddSecondCategory = (row: any) => {
  console.log(row);
  categoryDialogStatus.value.isShow = true;
  categoryDialogStatus.value.title = "新增二级分类";
  categoryDialogStatus.value.mode = DialogModeEnum.NEW;
  delete addCategoryParams.value.sceneId;
  addCategoryParams.value.parentId = row.id;
};

//
/**
 * 添加标签按钮
 * @param row
 */
const handleAddLabel = (row: any) => {
  addLabelsBo.value.categoryId = row.id;
  addLabelBo.value.categoryId = row.id;
  // 只能绑定产品标签
  getLabelParams.value.type = '0';
  getLabelParams.value.type = '0';
  addListLabelBo.value.type = '0';
  labelManagementDialogStatus.value.title = "添加分类标签";
  labelManagementDialogStatus.value.isShow = true;
  labelManagementDialogStatus.value.mode = LabelManagementDialogModeEnum.SELECT;
};

/**
 * 从分类中移出标签
 * @param row
 */
const removeLabelFromCategory = async (row: any) => {
  // 询问是否确定移出
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("确定移出该标签？", "提示", {
      type: "warning",
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消移除",
    });
  } else if (confirm === "confirm") {
    moveLabelBo.value.labelId = row.id;
    const [err, res] = await to(removeLabelFromCategoryApi(moveLabelBo.value));
    if (!err) {
      console.log(res);
      ElMessage({
        message: "移出成功",
        type: "success",
      });
      getLabelsBySecondCategoryId(currentSecondCategoryId.value);
      moveLabelBo.value.categoryId = currentSecondCategoryId.value;
    }
  }
};

/**
 * 修改场景状态
 * @param row
 */
const switchSceneStatus = async (row: any) => {
  if (row) {
    let switchSceneBo = { ...row };
    delete switchSceneBo.id;

    // 手动切换状态
    switchSceneBo.status = row.status == "0" ? "1" : "0";

    const [err] = await to(switchSceneApi(switchSceneBo));

    if (!err) {
      // 修改成功才更新状态值
      row.status = switchSceneBo.status;
      ElMessage({
        message: "修改成功",
        type: "success",
      });
    }
  }
};

/**
 * 修改分类状态
 * @param row
 */
const switchCategoryStatus = async (row: any) => {
  if (row) {
    let switchCategoryBo = { ...row };

    // 手动切换状态
    switchCategoryBo.status = row.status == "0" ? "1" : "0";

    const [err] = await to(switchCategoryApi(switchCategoryBo));

    if (!err) {
      // 修改成功才更新状态值
      row.status = switchCategoryBo.status;
      ElMessage({
        message: "修改成功",
        type: "success",
      });
    }
  }
};

/**
 * 处理删除场景
 * @param row
 */
const handleDeleteScene = async (row: any) => {
  // 弹出删除确认框
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确定删除选中的场景？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消删除",
    });
  } else if (confirm === "confirm") {
    const [err, res] = await to(deleteSceneApi(row.id));
    if (!err) {
      console.log(res);
      ElMessage({
        message: "删除成功",
        type: "success",
      });
    }
    getSceneList();
    if (currentSceneId.value === row.id) {
      firstCategoryList.value = [];
      secondCategoryList.value = [];
      categoryLabelList.value = [];
    }
  }
};

/**
 * 处理删除一级分类
 * @param row
 */
const handleDeleteFirstCategory = async (row: any) => {
  console.log(row);

  // 弹出删除确认框
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确定删除选中的分类？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消删除",
    });
  } else if (confirm === "confirm") {
    const [err, res] = await to(deleteCategoryApi(row.id));
    if (!err) {
      console.log(res);
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      if (currentFirstCategoryId.value === row.id) {
        secondCategoryList.value = [];
        categoryLabelList.value = [];
      } else {
        getSecondCategoryList();
      }
      getFirstCategoryList(currentSceneId.value);
    }
    // getSceneList();
  }
};

/**
 * 处理删除二级分类
 * @param row
 */
const handleDeleteSecondCategory = async (row: any) => {
  // 弹出删除确认框
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm("是否确定删除选中的分类？", "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );
  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消删除",
    });
  } else if (confirm === "confirm") {
    console.log(row);
    const [err, res] = await to(deleteCategoryApi(row.id));
    if (!err) {
      console.log(res);
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      // getSceneList();
      console.log(currentSecondCategoryId.value, row.id);

      if (currentSecondCategoryId.value === row.id) {
        categoryLabelList.value = [];
      } else {
        getSecondCategoryList();
        getLabelsBySecondCategoryId(row.id);
      }
      getSecondCategoryList();
    }
  }
};

/**
 * 处理新增
 */
const handleAddSubmit = () => {
  dialogFormRef.value.validate(async (valid: boolean) => {
    console.log(valid);
    if (addCategoryParams.value.sceneId) {
      // 新增一级分类
      const [err] = await to(addFirstCategoryApi(addCategoryParams.value));
      if (!err) {
        getFirstCategoryList(currentSceneId.value);
        ElMessage({
          message: "新增成功",
          type: "success",
        });
        categoryDialogStatus.value.isShow = false;
      }
    } else if (addCategoryParams.value.parentId) {
      // 新增二级分类
      const [err] = await to(addSecondCategoryApi(addCategoryParams.value));
      if (!err) {
        getSecondCategoryList();
        ElMessage({
          message: "新增成功",
          type: "success",
        });
        categoryDialogStatus.value.isShow = false;
      }
    } else {
      // 新增场景
      console.log(addSceneBo.value);
      const [err] = await to(addSceneApi(addSceneBo.value));
      if (!err) {
        getSceneList();
        ElMessage({
          message: "新增成功",
          type: "success",
        });
        sceneDialogStatus.value.isShow = false;
      }
    }

    // dialogStatus.value = Object.assign({}, initDialogStatus);
    // addCategoryParams.value = Object.assign({}, initAddCategoryParams);
    // addSceneBo.value = Object.assign({}, initAddSceneBo);
  });
};

/**
 * 处理编辑提交按钮
 */
const handleEditSubmit = () => {
  dialogFormRef.value.validate(async (valid: boolean) => {
    console.log(valid);
    if (addSceneBo.value.parentId === "0") {
      // 编辑场景
      const [err] = await to<BaseResponse<any>, any>(
        updateSceneDetailApi(addSceneBo.value),
      );
      if (!err) {
        ElMessage({
          message: "更新成功",
          type: "success",
        });
        getSceneList();
        sceneDialogStatus.value.isShow = false;
      }
    } else {
      // 编辑分类
      const [err] = await to<BaseResponse<any>, any>(
        updateCategoryDetailApi(addCategoryParams.value),
      );
      if (!err) {
        ElMessage({
          message: "更新成功",
          type: "success",
        });
        if (addCategoryParams.value.parentId) {
          getSecondCategoryList();
        } else {
          getFirstCategoryList(currentSceneId.value);
        }
        categoryDialogStatus.value.isShow = false;
      }
    }
    // dialogStatus.value = Object.assign({}, initDialogStatus);
    // addCategoryParams.value = Object.assign({}, initAddCategoryParams);
    // addSceneBo.value = Object.assign({}, initAddSceneBo);
  });
};

/**
 * 标签管理新增提交按钮
 */
const handleAddLabelSubmit = () => {
  dialogFormRef.value.validate(async (valid: boolean) => {
    console.log(addListLabelBo.value);
    if (valid) {
      // 有id表示编辑
      if (addListLabelBo.value.id) {
        if (addListLabelBo.value.url === "" || !addListLabelBo.value.url) {
          const [err] = await to<string, string>(
            ElMessageBox.confirm(
              "您还未上传标签图片，是否要继续操作?",
              "提示",
              {
                confirmButtonText: "是",
                cancelButtonText: "否",
                type: "warning",
              },
            ),
          );
          if (err === "cancel") {
            ElMessage({
              type: "info",
              message: "取消更新",
            });
            return;
          }
        }
        const [err] = await to<BaseResponse<any>, any>(
          updateLabelApi(addListLabelBo.value),
        );
        if (!err) {
          ElMessage({
            type: "success",
            message: "更新成功",
          });
          labelDialogStatus.value.isShow = false;
          console.log(2);

          getLabelList();
        }
      }
      // 无id表示新增
      else {
        if (addListLabelBo.value.url === "" || !addListLabelBo.value.url) {
          const [err] = await to<string, string>(
            ElMessageBox.confirm(
              "您还未上传标签图片，是否要继续操作?",
              "提示",
              {
                confirmButtonText: "是",
                cancelButtonText: "否",
                type: "warning",
              },
            ),
          );
          if (err === "cancel") {
            ElMessage({
              type: "info",
              message: "取消提交",
            });
            return;
          }
        }
        const [err] = await to<BaseResponse<any>, any>(
          addLabelApi(addListLabelBo.value),
        );
        if (!err) {
          ElMessage({
            type: "success",
            message: "添加成功",
          });
          labelDialogStatus.value.isShow = false;

          getLabelList();
        }
      }
    }
  });
};

// // 关闭dialog
// const closeDialog = () => {
//   dialogStatus.value = Object.assign({}, initDialogStatus);
//   addCategoryParams.value = Object.assign({}, initAddCategoryParams);
//   addSceneBo.value = Object.assign({}, initAddSceneBo);
// };

/**
 * 关闭编辑场景对话框
 */
const closeSceneDialog = () => {
  sceneDialogStatus.value = Object.assign({}, initSceneDialogStatus);
  addSceneBo.value = Object.assign({}, initAddSceneBo);
};

/**
 * 关闭编辑分类对话框
 */
const closeCategoryDialog = () => {
  categoryDialogStatus.value = Object.assign({}, initCategoryDialogStatus);
  addSceneBo.value = Object.assign({}, initAddSceneBo);
};

const closeLabelManagementDialog = () => {
  labelManagementDialogStatus.value = Object.assign(
    {},
    initLabelManagementDialogStatus,
  );
};

/**
 * 关闭编辑标签对话框
 */
const closeLabelDialog = () => {
  tagImg.value = null;
  dialogImageUrl.value = undefined;
  console.log(dialogImageUrl.value, tagImg.value);

  isSelected.value = false;
  isSelected2.value = false;

  isFinishUpload.value = false;
  addListLabelBo.value = Object.assign({}, initAddListLabelBo);
};

// 清空场景dialog
const sceneClose = () => {
  sceneDialogStatus.value = Object.assign({}, initSceneDialogStatus);
  addSceneBo.value = Object.assign({}, initAddSceneBo);
};

/**
 * 清空分类dialog
 */
const categoryClose = () => {
  categoryDialogStatus.value = Object.assign({}, initCategoryDialogStatus);
  addCategoryParams.value = Object.assign({}, initAddCategoryParams);
};

/**
 * 标签库的新增按钮
 */
const handleAddTableLabel = () => {
  labelDialogStatus.value.isShow = true;
  labelDialogStatus.value.title = "新增标签";
  labelDialogStatus.value.mode = DialogModeEnum.NEW;
};

/**
 * 获取所有标签列表，不泄露异常
 */
const getLabelList = async (): Promise<boolean> => {
  const [err, res] = await to<BasePageResponse<CourseLabelVo>, any>(
    getLabelListApi(getLabelParams.value),
  );
  if (!err) {
    console.log(res);
    labelList.value = res?.rows ?? [];
    total.value = Number(res?.total ?? 0);
    return true;
  }
  return false;
};

onMounted(() => {
  getSceneList();
  getLabelList();
});
</script>

<style scoped>
.card-header {
  display: flex;

  .text {
    width: 150px;
    /* background-color: aqua; */
  }

  .el-input {
    margin: 0 5px 0 0;
    width: 200px;
  }
}

.dialogFooter {
  margin: 30px 0 0 55%;
}
</style>
